# 第一步，导入模块
from rest_framework import  serializers
from .models import Book, Publish, Author

'''
bs = BookSerializer(queryset, many=True)
bs.data

ret = []
for obj in queryset:
    ret.append({
        "title":obj.title,
        "price":obj.price,
        "publish":obj.publish.pk,
        "authors":get_authors(obj),
    })
    
json.dumps(ret)
'''


"""
# 第二步 ,创建一个序列化类，字段类型不一定要跟models的字段一致
class BookSerializer(serializers.Serializer):
    title = serializers.CharField(max_length=32)
    price = serializers.DecimalField(max_digits=5,decimal_places=2)
    publish = serializers.CharField(max_length=32)
    # 外键字段，显示__str__方法的返回值
    publish_name = serializers.CharField(max_length=32,read_only=True,source='publish.name')
    publish_city = serializers.CharField(max_length=32,read_only=True,source='publish.city')
    # authors = serializers.CharField(max_length=32)   # book_obj.authors.all()
    # 多对多字段需要自己手动获取数据,SerializerMethodField()
    authors = serializers.SerializerMethodField()

    def get_authors(self,book_obj):
        author_list = []
        for author in book_obj.authors.all():
            author_list.append(author.name)
        return author_list

    def create(self, validate_data):
        validate_data['publish_id'] = validate_data.pop('publish')
        print("validate_date:",validate_data)
        book = Book.objects.create(**validate_data)

        return book
"""

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book        # 指定要操作的表
        fields = ('title',  # 要序列化的字段
                  'price',
                  'publish',
                  'authors',
                  'author_list',
                  'publish_name',
                  'publish_city'
        )
        extra_kwargs = {
            'publish': {'write_only': True},
            'authors': {'write_only': True}
        }

    publish_name = serializers.CharField(max_length=32,read_only=True,source='publish.name')
    publish_city = serializers.CharField(max_length=32,read_only=True,source='publish.city')
    write_only_fields = ("authors","publish")


    author_list = serializers.SerializerMethodField()

    def get_author_list(self, book_obj):
        # 拿到queryset开始循环
        authors = list()

        for author in book_obj.authors.all():
            authors.append(author.name)
        return authors


